#include "mqtt_module.hpp"

#ifndef YJ_MQTT_USE_CONFIG_H
#define YJ_MQTT_URL ("mqtt://139.9.73.201:1883")
#define YJ_MQTT_CLIENT_ID ("tunnel_test_dev1")
#define YJ_MQTT_USERNAME ("dev1")
#define YJ_MQTT_PASSWORD ("dev1")
#define YJ_MQTT_QOS (1)
#define YJ_MQTT_PUBLISH_TOPIC_SENSOR_DATA ("DEV_ID" "/" "DEV_ID" "/sensor_data/")
#define YJ_MQTT_PUBLISH_TOPIC_STATUS ("DEV_ID" "/" "DEV_ID" "/status/")
#define YJ_MQTT_SUBSCRIBE_TOPIC_CONTROL ("DEV_ID" "/" "DEV_ID" "/control/")
#endif // #ifndef YJ_MQTT_USE_CONFIG_H

using json = nlohmann::json;

yj_mqtt *mqtt_client = new yj_mqtt(YJ_MQTT_URL,
                                   YJ_MQTT_CLIENT_ID,
                                   YJ_MQTT_USERNAME,
                                   YJ_MQTT_PASSWORD,
                                   YJ_MQTT_QOS);

void test_mqtt_subscribe_thread()
{
    yj_return flag;

    mqtt_client->add_subscribe(YJ_MQTT_SUBSCRIBE_TOPIC_CONTROL);

    while (1)
    {
        flag = mqtt_client->start();
        LOG(INFO) << "mqtt start return a value:" << flag;
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }
}

void test_mqtt_publish_thread()
{
    while (1)
    {
        json time_stamp;
        time_stamp["time"] = yj_time_get_format_ms();

        mqtt_client->publish(YJ_MQTT_PUBLISH_TOPIC_STATUS,time_stamp.dump());
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }
}


void  test_mqtt_read_thread()
{
    json j;
    std::vector<std::string> data;
    while (1)
    {
        mqtt_client->get_recv_vector(data);
        if(data.size() == 0)
        {
            
            LOG(INFO) << "mqtt recv data is empty";
        }

        for (int count = 1;auto &i : data)
        {
            LOG(INFO) << "mqtt recv data:" << i << " count:" << count;
            try
            {
                j = json::parse(i);
                LOG(INFO) << "mqtt recv json data:" << j.dump(4);
                LOG(INFO) << "mqtt recv json intext :" << j["time"];
            }
            catch(const std::exception& e)
            {
                LOG(ERROR) << e.what() ;
            }
            count++;
        }
        data.clear();
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main()
{
    mqtt_client->init();
    std::thread mqtt_subscribe_thread(test_mqtt_subscribe_thread);
    std::thread mqtt_publish_thread(test_mqtt_publish_thread);
    std::thread mqtt_read_thread(test_mqtt_read_thread);


    // 等待从键盘输入一个字符
    std::cin.get();

    mqtt_subscribe_thread.join();
    mqtt_publish_thread.join();
    mqtt_read_thread.join();
    return 0;
}